Ext.define('FrontSuite.controller.Database', {
    extend: 'Ext.app.Controller',

    init: function () {
        FrontSuite.db = this;
    },

    getTableDefCols: function (viewDef, data) {
         var db = this;
         var columnConfigArray    = [];
         var doAutoColWidth = 1;

         for (var i = 0; i < viewDef['columns'].length; i++) {
             var column_name = viewDef.columns[i];
             var columnConfig;
             if (viewDef['column'][column_name]) {
                 //var column_label  = viewDef['column'][column_name].column_label;
                 var column_width         = viewDef['column'][column_name].display_width;
                 var column_hidden        = viewDef['column'][column_name].hidden;
                 var default_column_width = column_name.length*8 + 20;
                 var column_filter_value  = viewDef['column'][column_name].filter;
                 var column_sort_value    = viewDef['column'][column_name].sort;
                 var column_label         = viewDef['column'][column_name].column_label;
                 var column_type          = viewDef['column'][column_name].column_type;

                 if (column_width == null) {
                     column_width = default_column_width;
                 }
                 else {
                     doAutoColWidth = 0;
                 }

                 if (column_hidden == null) {
                     column_hidden = false;
                 }

                 if (!column_label) {
                     column_label = column_name;
                 }

                 columnConfig = {header : column_label, sortable : true, dataIndex : column_name,
                     width : column_width, filterable : true, hidden : column_hidden, type : column_type, editor: { xtype: 'textfield' },
                     listeners: {headertriggerclick: function(obj, col) {db.createFormatStore(obj, col, data);}}
                 };

                 if (column_filter_value) {
                     columnConfig.filter = {value: column_filter_value, active: true};
                 }

                 if (column_sort_value && data.sorters == null) {
                     columnConfig.sort   = column_sort_value;
                     data.sorters = {property: column_name, direction : column_sort_value};
                 }
             }
             else {
                 // TODO: Figure out why the server EVER returns columns which are not in the viewDef['column'] hash.
                 //       This is the safety-net work-around.
                 columnConfig = {header : column_name, sortable : true, dataIndex : column_name, filterable : true};
             }

             columnConfigArray.push(columnConfig);
         }

         if (data != null) {
             data.doAutoColWidth = doAutoColWidth;
             //console.log('auto_width: '+data.doAutoColWidth);
         }

         //console.log(columnConfigArray);
         return (columnConfigArray);
    },

    getTableDefColsSql: function (viewDef, data) {
         var columnConfigArray    = [];
         var doAutoColWidth = 1;

         for (var i = 0; i < viewDef['columns'].length; i++) {
             var column_name = viewDef.columns[i];
             var columnConfig;
             if (viewDef['column'][column_name]) {
                 var column_width         = viewDef['column'][column_name].display_width;
                 var column_hidden        = viewDef['column'][column_name].hidden;
                 var default_column_width = column_name.length*8 + 20;
                 var column_label                = viewDef['column'][column_name].column_label;
                 var column_type          = viewDef['column'][column_name].column_type;

                 if (column_width == null) {
                     column_width = default_column_width;
                 }
                 else {
                     doAutoColWidth = 0;
                 }

                 if (column_hidden == null) {
                     column_hidden = false;
                 }

                 if (!column_label) {
                     column_label = column_name;
                 }

                 columnConfig = {header : column_label, sortable : false, dataIndex : column_name,
                     width : column_width, hidden : column_hidden, type : column_type};
             }
             else {
                 // TODO: Figure out why the server EVER returns columns which are not in the viewDef['column'] hash.
                 //       This is the safety-net work-around.
                 columnConfig = {header : column_name, dataIndex : column_name, sortable : false};
             }

             columnConfigArray.push(columnConfig);
         }

         if (data != null) {
             data.doAutoColWidth = doAutoColWidth;
         }

         return (columnConfigArray);
    },

    getTableDefRels : function (viewDef, relationship, relationships) {
        var rel = viewDef['relationship'];

        if (rel) {
            for(var key in rel) {
                relationship[key] = rel[key];
            }

            for (var i = 0; i < viewDef['relationships'].length; i++) {
                relationships.push(viewDef.relationships[i]);
            }
        }
    },

    getTableDef: function (args) {
        if (args.tabid) {

            var dbParts    = args.tabid.split('.');
            var dbName     = dbParts[0];
            var tableName  = dbParts[1];
            var obj        = this;

            Ext.Ajax.request({
                url       : FrontSuite.options.apps_urldir+'/sitefront/front-framework/api.php/object/'+dbName+'/'+tableName+'/_meta',
                params    : {view : args.tabid},
                method    : 'GET',
                autoAbort : false,
                success: function (response, opts) {
                    var metadataResponse = Ext.JSON.decode(response.responseText);
                    var viewDef          = metadataResponse.data;
                    if (args.success) (args.success)(args.tabid, viewDef);
                    else              FrontSuite.app.notify({object: 'Application', method: 'getTableDef', message: response.responseText});
                },
                failure: function(response, opts) {
                    if (args.failure) (args.failure)(response, opts);
                    else              FrontSuite.app.error({object: 'Application', method: 'getTableDef', message: response.status});
                }
            });
        }
        else {
            FrontSuite.app.error({object: 'Application', method: 'getTableDef', message: 'called with no tabid'});
        }
    },

    createFormatStore: function (obj, col, results) {
        var formatComboMenu = Ext.getCmp('formatComboMenu.' + results.id);
        if (formatComboMenu) {
            if (col.type == 'integer') {
                var formatStore = Ext.create('Ext.data.ArrayStore', {
                    fields : ['id'],
                    data   : [['default'],['0,000']]
                });
                formatComboMenu.bindStore(formatStore);
            }
            else if (col.type == 'float') {
                var formatStore = Ext.create('Ext.data.ArrayStore', {
                    fields : ['id'],
                    data   : [['default'],['0,000.00'],['0,000.0000'],
                        ['0.00'],['0.0000'],['0.000000'],['0.000.000000']]
                });
                formatComboMenu.bindStore(formatStore);
            }
            else if (col.type == 'string') {
                var formatStore = Ext.create('Ext.data.ArrayStore', {
                    fields : ['id'],
                    data   : [['default'],['uppercase'],['lowercase']]
                });
                formatComboMenu.bindStore(formatStore);
            }
            else if (col.type == 'datetime') {
                var formatStore = Ext.create('Ext.data.ArrayStore', {
                    fields : ['id'],
                    data   : [['default'],['Y-m-d H:i:s'],['m/d/Y H:i:s']]
                });
                formatComboMenu.bindStore(formatStore);
            }
            else if (col.type == 'date') {
                var formatStore = Ext.create('Ext.data.ArrayStore', {
                    fields : ['id'],
                    data   : [['default'],['TBD date']]
                });
                formatComboMenu.bindStore(formatStore);
            }
        }
    }
});
